#include"http_server.h"
#include"form_parser.h"

namespace sylar{
namespace http{
static sylar::Logger::ptr g_logger = SYLAR_LOG_NAME("system");


HttpServer::HttpServer(bool keepalive
        ,sylar::IOManager* io_worker
        ,sylar::IOManager* accept_worker)
    :TcpServer(io_worker, accept_worker)
    ,m_isKeeplive(keepalive) {
    m_dispatch.reset(new ServletDispatch);

}

void HttpServer::downloadPic(HttpRequest::ptr req){
    auto body = req->getBody();
    std::string content_type = req->getHeader("Content-Type");
    std::string content_length = req->getHeader("Content-Length");
    SYLAR_LOG_INFO(g_logger)<<"content_type:"<<content_type<<" content_length:"<<content_length
            <<" body size:"<<body.size();
    auto posi = content_type.rfind("boundary=");

    // std::ofstream ofs;
    // ofs.open("/home/wty/sylar_learn/bin/post_file.txt", std::ios::out);
    // ofs<<body;
    // ofs.close();

    std::string boundary(content_type.substr(posi+9));

    int64_t content_start_posi = body.find("\r\n\r\n")+4;
    int64_t content_size = (body.rfind(boundary)-content_start_posi);
    SYLAR_LOG_INFO(g_logger)<<" content size:"<< content_size;

    std::ofstream pic;
    pic.open("/home/wty/sylar_learn/bin/post_pic.jpg", std::ios::out|std::ios::binary);
    pic<<body.substr(content_start_posi, content_size);
    pic.close();
}


void HttpServer::handleClient(Socket::ptr client) {
    //SYLAR_LOG_DEBUG(g_logger) << "handleClient " << *client;
    HttpSession::ptr session(new HttpSession(client));
    do {
        auto req = session->recvRequest();
        if(!req) {
            SYLAR_LOG_DEBUG(g_logger) << "recv http request fail, errno="
                << errno << " errstr=" << strerror(errno)
                << " cliet:" << *client << " keep_alive=" << m_isKeeplive;
            break;
        }

        HttpResponse::ptr rsp(new HttpResponse(req->getVersion()
                            ,req->isClose() || !m_isKeeplive));
        rsp->setHeader("Server", getName());
        // rsp->setBody("hello world");
        m_dispatch->handle(req, rsp, session);
        session->sendResponse(rsp);
        if(!m_isKeeplive || req->isClose()) {
            break;
        }
        // SYLAR_LOG_INFO(g_logger)<< "request:"<<std::endl<<*req;
        if(req->getMethod()==HttpMethod::POST){
            downloadPic(req);
        }
        // SYLAR_LOG_INFO(g_logger)<< "rsp:"<<std::endl<<*rsp;

    } while(true);
    session->close();
}

}
}